package com.lanou.horo.zhuizhui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.horo.zhuizhui.adapter.PictureContentAdapter;
import com.lanou.horo.zhuizhui.entity.HomePageItem;
import com.lanou.horo.zhuizhui.entity.PictureNewItem;
import com.lanou.horo.zhuizhui.entity.SearchIconItem;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.utility.clickInterface.HomePageItemClickListener;
import com.lanou.horo.zhuizhui.utility.recyclerView.SpacesItemDecoration;
import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.activity.SpaceImageDetailActivity;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/28.
 */
public class PictureContentFragment extends Fragment implements HomePageItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private PictureContentAdapter adapter;
    private RequestQueue queue;
    private SwipeRefreshLayout swipeRefreshWidget;
    private Handler handler;
    private RecyclerView.LayoutManager layoutManager;
    private int lastVisibleItem;
    private String url;
    private boolean isdialogshowing = false;
    private CustomProgressDialog dialog;


    public PictureContentFragment(String url) {
        this.url = url;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_picture_new, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.pictureNewRecyclerView);
        swipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dialog = new CustomProgressDialog(getActivity(), "加载中...", R.anim.loding);

        dialog.setCanceledOnTouchOutside(false);
        layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        swipeRefreshWidget.setRefreshing(true);
                        if (adapter.getEntityList() != null) {
                            adapter.getEntityList().clear();
                            initData();
                        }
                        break;
                }
            }
        };
        swipeRefreshWidget.setColorSchemeColors(0xff00aa00, 0xfffedcba, 0xff123456, 0xff654321);
        swipeRefreshWidget.setOnRefreshListener(this);
        swipeRefreshWidget.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources()
                        .getDisplayMetrics()));
//        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView,
//                                             int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE
//                        && lastVisibleItem + 1 == adapter.getItemCount()) {
//                    swipeRefreshWidget.setRefreshing(true);
//                    // 此处在现实项目中，请换成网络请求数据代码，sendRequest .....
//                    handler.sendEmptyMessageDelayed(0, 3000);
//                }
//            }
////            @Override
////            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
////                super.onScrolled(recyclerView, dx, dy);
////                lastVisibleItem = layoutManager.findViewByPosition();
////                        //.findLastVisibleItemPosition();
////            }
//
//        });
        swipeRefreshWidget.setProgressViewEndTarget(true, 100);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PictureContentAdapter(getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setItemClickListener(this);
        SpacesItemDecoration decoration = new SpacesItemDecoration(00);
        recyclerView.addItemDecoration(decoration);
        initData();

    }

    private void initData() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        queue = Volley.newRequestQueue(getActivity());
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                PictureNewItem pni = gson.fromJson(response, PictureNewItem.class);
                if (pni != null) {
                    List<PictureNewItem.WelfaresEntity> list = pni.getWelfares();
                    if (list != null && list.size() > 0) {
                        adapter.addWelList(list);
                    }
                }
                swipeRefreshWidget.setRefreshing(false);
                if (isdialogshowing == true) {
                    dialog.dismiss();
                    isdialogshowing = false;
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }

    @Override
    public void homePageItemClick(HomePageItem.ListsEntity hlid) {
    }


    @Override
    public void pictureItemClick(PictureNewItem.WelfaresEntity pnwe, int itemPosition,
                                 List<String> imgurl, ImageView imageView) {
        Intent intent = new Intent(getActivity(), SpaceImageDetailActivity.class);
        intent.putExtra("images", (ArrayList<String>) imgurl);
        intent.putExtra("position", itemPosition);
        int[] location = new int[2];
        imageView.getLocationOnScreen(location);
        intent.putExtra("locationX", location[0]);
        intent.putExtra("locationY", location[1]);
        intent.putExtra("width", imageView.getWidth());
        intent.putExtra("height", imageView.getHeight());
        startActivity(intent);
        getActivity().overridePendingTransition(0, 0);
    }

    @Override
    public void searcherItemClick(SearchIconItem.ThemesEntity stid) {
    }

    @Override
    public void homeItemClick(HomePageItem.ListsEntity.ThemeListEntity hlt) {

    }


    @Override
    public void onRefresh() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        handler.sendEmptyMessageDelayed(0, 3000);
    }
}
